<template>
    <div class="container" ref="scrollDiv" v-loading="loading" :element-loading-text="text">
        <!-- 工具栏 -->
        <Toolbar class="toolbar" :editor="editorRef" :defaultConfig="toolbarConfig" v-if="operateFlag == -1" />
        <div style="width:1040px;margin: 0 auto;background-color: antiquewhite;" v-if="operateFlag == -1">
            <!-- 标题 -->
            <div class="title">
                <el-input v-model="title" type="text" placeholder="请输入标题（最多 100 个字）" />
            </div>
            <!-- 内容 -->
            <Editor
                style="height: 580px; margin: 0 auto;overflow-y: hidden; width: 1020px;text-align: left;font-size: 15px;"
                v-model="valueHtml" :defaultConfig="editorConfig" @onCreated="handleCreated" />

            <!-- 设置作品信息 -->
            <div class="creation-info">
                <h2>
                    <el-icon>
                        <Tools />
                    </el-icon>
                    文章设置
                </h2>
                <!-- 添加封面 -->
                <div class="set-cover">
                    <span style="margin-right: 20px">设置作品封面</span>
                    <ImgUpload @sendData="getImgUrl" :width="coverWidth" :height="coverHeight" />
                </div>
                <!-- 设置标签 -->
                <div class="set-tags">
                    <span style="margin-right: 20px">添加领域标签</span>
                    <el-select :disabled="tagsOfChioce.length >= 5" v-model="tagsOfChioce" multiple
                        placeholder="请选择标签（最多 5 个）" style="width:60%;">
                        <el-option v-for="item, index in tags" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                    <el-icon :size="30" style="margin-left: 20px;" @click='tagsOfChioce = []'>
                        <Delete />
                    </el-icon>
                </div>
            </div>
        </div>

        <!-- 底栏 -->
        <div class="footer" v-if="operateFlag == -1">

            <div style="cursor: pointer;" @click="scrollToBottom"><el-icon>
                    <Setting />
                </el-icon> 文章设置</div>
            <!-- 字数 -->
            <div style="display: flex; width: 200px;">
                <div>当前字数：</div>
                <div v-if="editorRef != null"> {{ editorRef.getText().length + title.length }}</div>
            </div>
            <div style="width: 400px;display: flex;align-items: center;justify-content: end;">
                
                <el-button plain :icon="DocumentRemove" type="warning" @click="publishArticle(0)">保存草稿</el-button>
                <el-button plain :icon="Promotion" type="success" @click="publishArticle(1)">发布文章</el-button>
            </div>
        </div>

        <!-- 保存成功 -->
        <el-result v-if="operateFlag == 0" icon="success" title="保存成功" sub-title="点击返回到首页">
            <template #extra>
                <el-button type="primary" @click="router.push('/home')">前往首页</el-button>
            </template>
        </el-result>

        <!-- 发布成功 -->
        <el-result v-if="operateFlag == 1" icon="success" title="发布成功" sub-title="点击快速查看发布详情">
            <template #extra>
                <el-button type="primary" @click="handleDetails">查看详情</el-button>
            </template>
        </el-result>

    </div>
</template>

<script setup lang="ts">
import { DocumentRemove, Promotion } from '@element-plus/icons-vue'
import ImgUpload from '@/components/ImgUpload.vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, nextTick, reactive } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getTags } from '@/api/tag'
import { ElMessage } from 'element-plus'
import store from '@/store'
import { addCreation } from '@/api/creation'
import { useRouter } from 'vue-router'

const router = useRouter()

//加载
const loading = ref(false)
const text = ref('正在发布...')

//操作(-1没有任何操作,0保存草稿,1发布文章)
const operateFlag = ref(-1)

//作品信息
const creation = reactive({
    title: '',
    content: '',
    tag: '',
    cover: '',
    isFinish: 0,
    type: '文章',
    authorId: store.getters.getloginInfo.username
})
//封面尺寸
const coverWidth = ref('200px')
const coverHeight = ref('120px')

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
//标题
const title = ref('')
// 内容 HTML
const valueHtml = ref('')
//标签
const tags: any = ref([])
//标签选择
const tagsOfChioce = ref([])
// 模拟 ajax 异步获取内容
onMounted(() => {
    getTags().then(res => {
        tags.value = res.data.data
    })
})

const toolbarConfig = { excludeKeys: ['fullScreen'] }
const editorConfig = { placeholder: '请输入正文...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

// 上传的图片
const getImgUrl = (url: string) => {
    creation.cover = url
}

// 滚到页底部
const scrollDiv = ref()
const scrollToBottom = () => {
    let scrollElem = scrollDiv.value!;
    scrollElem.scrollTo({ top: scrollElem.scrollHeight, behavior: 'smooth' });
}

//检查信息
const checkInfo = () => {
    if (title.value.length == 0) {
        ElMessage.error('标题不能为空！')
        return false
    }
    if (title.value.length > 100) {
        ElMessage.error('标题不能超过 100 个字！')
        return false
    }
    if (editorRef.value.getText().length == 0 || editorRef.value == null) {
        ElMessage.error('您输入的内容为空！')
        return false
    }
    if (tagsOfChioce.value.length < 3) {
        ElMessage.error('请选择标签至少 3 个标签')
        return false
    }
    return true
}

//发布（保存）作品
const publishArticle = async (status: number) => {
    if (checkInfo()) {
        creation.title = title.value
        creation.content = editorRef.value.getHtml()
        creation.tag = tagsOfChioce.value.join(',')
        if (status == 0) {
            creation.isFinish = 0
        } else if (status == 1) {
            creation.isFinish = 1
        }
        loading.value = true
        await addCreation(creation).then(res => {
            if (res.flag) {
                nextTick(() => {
                    // 清空数据
                    editorRef.value.setHtml('')
                    title.value = ''
                    tagsOfChioce.value = []
                    creation.cover = ''
                    //弹出操作结果
                    loading.value = false
                    if (status == 0) {
                        operateFlag.value = 0
                    } else if (status == 1) {
                        operateFlag.value = 1
                    }
                })

            }
        })
    }
}

//跳转到详情页
const handleDetails = () => {
    router.push({
        path: '/home',
    })
}

</script>

<style scoped>
.container {
    height: 100%;
    overflow: scroll;
    width: 1400px;
    margin: 0 auto;

    .toolbar {
        margin: 0 auto;
        width: 1350px;
        border: none;
        box-shadow: none;
    }

    .creation-info {
        margin: 0 auto;
        width: 1020px;
        height: 450px;
        background-color: rgb(233, 236, 241);
        padding: 10px;
        font-size: 16px;
    }


    /* 标题输入框 */
    .title {
        margin: 0 auto;
        width: 1020px;
    }

    ::v-deep .el-input__wrapper {
        background-color: #ffffff;
        height: 60px;
        border: none;
        font-weight: bold !important;
        margin-top: 1px;
        border-radius: 0px;
        color: black;
        font-size: 25px;
        box-shadow: none;
    }

    ::v-deep .el-input__inner {
        color: black;
        font-weight: bold;
    }

    ::v-deep .w-e-bar-item button {
        font-size: 17px;
    }

    ::v-deep .el-select__wrapper {
        height: 40px;
    }


    .footer {
        position: fixed;
        width: 1400px;
        height: 50px;
        background-color: rgb(255, 255, 255);
        bottom: 0;
        display: flex;
        padding-left: 100px;
        padding-right: 100px;
        line-height: 50px;
        box-sizing: border-box;
        min-width: 0;
        color: #8491a5;
        font-size: 16px;
        justify-content: space-around;
        z-index: 999;

        .el-button {
            border: none;
        }
    }

    .set-cover {
        margin-left: 10px;
        margin-top: 30px;
        display: flex;
    }

    .set-tags {
        display: flex;
        padding: 10px;
        margin-top: 20px;
        height: 60px;
        line-height: 60px;
        align-items: center;
    }

    ::v-deep .el-tag {
        background-color: #ecf5ff;
        display: flex;
        height: 30px;
        padding: 0 10px;
        line-height: 30px;
        font-size: 14px;
        color: #409eff;
        border: 1px solid #d9ecff;
        border-radius: 4px;
        box-sizing: border-box;
        white-space: nowrap;
    }

}
</style>